iT邦幫忙

2024 iThome 鐵人賽

DAY 1
0
佛心分享-刷題不只是刷題

C/C++ 刷題30天系列 第 1

Day01_C語言刷LeetCode

  • 分享至 

  • xImage
  •  

想說藉由鐵人賽來督促自己刷題,希望自己能堅持30天~
至少每天刷一題~
主要的刷題會以C來刷題,如果遇到STL的話就會改成使用C++就是了~

主要的刷題主題會以(來自PTT大神們提供的主題們)

  1. Sizeof
  2. Bitwise
  3. Pointer
  4. Function Pointer
  5. Volatile
  6. Little endian and Big endian
  7. Linked list
  8. Sort
  9. Tree

畢竟是要連續30天,所以Day1就開始解LeetCode吧!

141. Linked List Cycle

tags: Easy、Linked-List

Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.

解法:

使用快慢指針來解題,就是如果快慢指針相遇代表有Cycle(pos值等於相遇到的Node),如果沒有相遇代表沒有Cycle(pos=-1)
時間複雜度: O(n) 空間複雜度: O(1)
Code:

bool hasCycle(struct ListNode *head) {
    int pos = -1;
    int index = 0; /*回傳在哪一個Node相遇*/
    struct ListNode *slow = head;
    struct ListNode *fast = head;
    
    while (fast != NULL && fast->next != NULL) {
        slow = slow->next;
        fast = fast->next->next;
        
        if (slow == fast) {
            slow = head;
            while (slow != fast) {
                slow = slow->next;
                fast = fast->next->next;
                index++;
            }
            pos = index ;
            return true;
        }
    }
    return false;
}

Floyd Cycle Detection Algorithm_龜兔賽跑演算法

解法就是使用慢指針(一次跑一格)與快指針(一次跑兩格),因為兩者速度不同,如果List結構存在循環,就一定會在某一點碰到(回傳的pos值)
圖片解說:
https://hackmd.io/_uploads/rJtZGzi90.png


下一篇
Day02__C語言刷LeetCode
系列文
C/C++ 刷題30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言